package com.controller.resource;

import com.domain.*;
import com.server.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value="/resource")
public class ResourceController {

    @Resource(name = "discussService")
    private DiscussService discussService;

    @Resource(name="memberService")
    private MemberService memberService;

    @Resource(name = "spaceService")
    private SpaceService spaceService;

    @Resource(name="resourceService")
    private ResourceService resourceService;

    @Resource(name="contributeService")
    private ContributeService contributeService;

    @Resource(name="documentService")
    private DocumentService documentService;

    @Resource(name="commentService")
    private CommentService commentService;

    @Resource(name="replyService")
    private ReplyService replyService;

    @Resource(name = "userService")
    private UserService userService;

    //通用页面跳转控制器
    @RequestMapping(value="/{formName}")
    public String f(@PathVariable String formName){
        return formName;
    }

    //显示所有资源
    @RequestMapping(value="/space-resource")
    public String showResource(@RequestParam(value="page",defaultValue="1")int page,
                               @RequestParam(value="pageSize",defaultValue="8")int pageSize,
                               Model model,HttpServletRequest request,HttpSession session)throws Exception{
        //获取空间id值
        Space space= (Space) session.getAttribute("space");
        Integer space_id=space.getId();
        System.out.println("输出space_id的值："+space_id);
        System.out.println("space_id==="+space_id);
        Space spaceSeesion=spaceService.selectSpaceById(space_id);
        session.setAttribute("space",spaceSeesion);
        model.addAttribute("space",spaceSeesion);
        //计算资源总数：
        int resourceTotal=resourceService.findResourceTotal(space_id);
        session.setAttribute("resourceTotal",resourceTotal);
        //计算话题总数：
        int discussTotal = discussService.findDiscussTotal(space_id);
        session.setAttribute("discussTotal",discussTotal);
        //计算贡献总数：
       // int contributeTotal=contributeService.showContributeTotal(space_id);

        //计算成员总数：
        int memberCount=memberService.findMemberTotal(space_id);
        session.setAttribute("memberCount",memberCount);

        List<Resources> relist=resourceService.findAllByPage(space_id,page,pageSize);
        List<Resources> resourceslist=resourceService.showResource(space_id);
        session.setAttribute("resourceslist",resourceslist);
//        Integer resourceTotal=resourceService.findResourceTotal(space_id);
        Integer contributeTotal=(Integer) contributeService.showContributeTotal(space_id);
        session.setAttribute("contributeTotal",contributeTotal);
        if(resourceTotal==0){
            model.addAttribute("all",0);
        }else{
            model.addAttribute("all",resourceTotal);
        }
        //计算总页数
        if((resourceTotal/pageSize)<1){
            model.addAttribute("all",1);
        }else {
            if (resourceTotal % pageSize!=0) {
                int pageTotal = new Integer(resourceTotal / pageSize + 1);
                model.addAttribute("all", pageTotal);
            } else {
                int pageTotal = new Integer(resourceTotal / pageSize);
                model.addAttribute("all", pageTotal);
            }
        }
        model.addAttribute("relist",relist);
        model.addAttribute("currentPage",page);

        return "space-resource";
    }

    //根据资源id显示资源
    @RequestMapping(value="/space-resourceShow")
    public String showResourceById(@RequestParam("id") Integer id,@RequestParam("space_id") Integer space_id,Model model,HttpSession session)throws Exception{
        Space spaceById=spaceService.selectSpaceById(space_id);
        String name=spaceById.getName();
        int userId=spaceById.getUserId();
        Space space=spaceService.selectSpaceByNameAndUserId(name,userId);
        session.setAttribute("space",space);
        //根据资源id显示资源信息
        Resources resource=resourceService.showResourceByIdAndSpaceId(id,space_id);
        session.setAttribute("resource",resource);
        //根据资源id显示附件信息
        List reAndDolist=documentService.showDocumentByResourceId(id);
        model.addAttribute("reAndDolist",reAndDolist);
        //根据资源id显示评论信息
        List commentList=commentService.showCommentByResourceId(id);
        model.addAttribute("commentList",commentList);
        //根据评论id显示回复信息
        List replyList=replyService.selectAllReply();
        model.addAttribute("replyList",replyList);
        //计算资源总数：
        int resourceTotal=resourceService.findResourceTotal(space_id);
        session.setAttribute("resourceTotal",resourceTotal);
        //计算话题总数：
        int discussTotal=discussService.findDiscussTotal(space_id);
        session.setAttribute("discussTotal",discussTotal);
        //计算贡献总数：
        int contributeTotal=contributeService.showContributeTotal(space_id);
        session.setAttribute("contributeTotal",contributeTotal);
        //计算成员总数：
        int memberCount=memberService.findMemberTotal(space_id);
        session.setAttribute("memberCount",memberCount);
        return "space-resource-show";
    }

    //根据资源id显示资源
    @RequestMapping(value="/space-resource-show")
    public String showResourceById(@RequestParam("id") Integer id,Model model,HttpSession session)throws Exception{
        //根据资源id显示资源信息
        Resources resource=resourceService.showResourceById(id);
        session.setAttribute("resource",resource);
        //根据资源id显示附件信息
        List reAndDolist=documentService.showDocumentByResourceId(id);
        model.addAttribute("reAndDolist",reAndDolist);
        //根据资源id显示评论信息
        List<Comment> commentList=commentService.showCommentByResourceId(id);
        model.addAttribute("commentList",commentList);
        for(int i=0;i<commentList.size();i++){
            Comment comment=commentList.get(i);
            System.out.println("评论======="+comment);
            User user=comment.getUser();
            System.out.println("用户为======="+user);
        }
        //根据评论id显示回复信息
        List replyList=replyService.selectAllReply();
        model.addAttribute("replyList",replyList);
        return "space-resource-show";
    }

    //根据id删除资源
    @RequestMapping(value="/deleteByResource")
    public String deleteByResourceId(Resources re)throws Exception{
        Integer id=re.getId();
        resourceService.deleteByResourceId(id);
        return "redirect:space-resource";
    }

    //显示所有附件信息
    @RequestMapping(value="/space-resource-filelist")
    public String showDocument(@RequestParam(value="page",defaultValue="1")int page,
                               @RequestParam(value="pageSize",defaultValue="8")int pageSize,Model model,HttpSession session)throws Exception{
        //获取空间id值
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("输出space_id的值："+space_id);

        List<Document> flist=documentService.findAllFileByPage(space_id,page,pageSize);
        //搜索所有的附件信息
        List<Document> documentslist=documentService.showDocument(space_id);
        //计算总页数
        int all;
        if((documentslist.size()/pageSize)<1){
            model.addAttribute("all",1);
        }else{
            if(documentslist.size()%pageSize!=0){
                all=documentslist.size()/pageSize+1;
                model.addAttribute("all",all);
            }else{
                all=documentslist.size()/pageSize;
                model.addAttribute("all",all);
            }
        }
        model.addAttribute("flist",flist);
        model.addAttribute("currentPage",page);
        return "space-resource-filelist";
    }

    //搜索信息——模糊查询
    @RequestMapping(value="/select",method = RequestMethod.POST)
    public String select(@RequestParam("title") String title,@RequestParam("author")String author,
                         @RequestParam("label")String label,Model model,HttpSession session){
        //获取空间id值
        Space space= (Space)session.getAttribute("space");
        Integer space_id=space.getId();
        System.out.println("输出space_id的值："+space_id);
        //根据资源名，作者，标签进行模糊查询
        List selectlist=resourceService.BlurredSelect(space_id,title,author,label);
        System.out.println(selectlist);model.addAttribute("selectlist",selectlist);
        return "space-resource-search";
    }

    //下载文件
    @RequestMapping(value="download")
    public ResponseEntity<byte[]> download(@RequestParam("id") Integer id,@RequestParam("filename") String filename,
                                           @RequestParam("downloadcount") Integer downloadcount,
                                           HttpSession session,HttpServletRequest request)throws Exception{
        downloadcount=downloadcount+1;
        documentService.updateNum(id,downloadcount);

        //获取目录/路径
        String path=session.getServletContext().getRealPath("/filelist");
        //编码方法
        String downloadFileName=new String(filename.getBytes("ISO-8859-1"),"UTF-8");
        File file=new File(path+File.separator+downloadFileName);
        byte[] body=null;
        InputStream is=new FileInputStream(file);
        body=new byte[is.available()];
        is.read(body);
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition","attchement;filename="+file.getName());
        HttpStatus statusCode=HttpStatus.OK;
        ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(body,headers,statusCode);
        return entity;
    }

    //修改资源1
    @RequestMapping(value="update")
    public String update(Resources re,HttpSession session,Model model) throws Exception{
        Integer id=re.getId();
        //根据资源id查找资源信息
        Resources resourceupdate=resourceService.showResourceById(id);
        System.out.println(resourceupdate);
        //根据资源id查找附件信息
        List<Document> file=documentService.showDocumentByResourceId(id);
        System.out.println(file);
        model.addAttribute("file",file);
        session.setAttribute("resourceupdate",resourceupdate);
        return "space-resource-update";
    }

    //修改资源2
    @RequestMapping(value="update_commit",method = RequestMethod.POST)
    public String update_commit(@RequestParam("id")Integer id,@RequestParam("title")String title,
                                @RequestParam("detail")String detail,@RequestParam("label")String label,
                                @RequestParam("file") MultipartFile file,Model model,
                                HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception{
        //获取当前时间为修改时间和创建时间
        Date createdate=new Date();
        Date updatetime=new Date();
        //获取member_id就是用户id
        User user= (User) session.getAttribute("user");
        Integer member_id=user.getId();
        Integer resource_id=id;
        Integer contrbute_id=resource_id;
        //新上传的文件下载数为0
        Integer downloadcount=0;
        Space space= (Space) session.getAttribute("space");
        Integer space_id=space.getId();

        //设置请求和响应的编码统一为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //拿到编辑器的内容
        String content = request.getParameter("editorValue");
        //如果不为空
        if(content != null){
            //将内容设置进属性
            request.setAttribute("content",content);
        }else{
            response.getWriter().append("内容为空!");
        }
        resourceService.updateResource(id,title,content,detail,label,updatetime);

        if (!file.isEmpty()||file!=null) {
            // 获取文件名
            String filename = file.getOriginalFilename();
            System.out.println("上传的文件名为：" + filename);
            //获取文件的大小
            double filesize=file.getSize();
            // 文件上传后的路径
            String filePath=session.getServletContext().getRealPath("/filelist/"+filename);
            File dest = new File(filePath);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            documentService.insertDocument(filename,filesize,createdate,downloadcount,member_id,resource_id,space_id,contrbute_id);
        }

        return "redirect:space-resource-show?id="+id;
    }

    //发布资源——富文本框
    @RequestMapping(value="/insert_commit",method = RequestMethod.POST)
    public String inseinsert_commitrt(@RequestParam("title") String title,@RequestParam("detail")String detail,
                                      @RequestParam("file") MultipartFile file,Document document,@RequestParam("label")String label,
                                      HttpServletRequest request, HttpServletResponse response,HttpSession session)throws Exception{
        //设置当前时间为创建时间
        Date createdate=new Date();
        Date updatetime=new Date();
        //获取space_id
        Space space= (Space) session.getAttribute("space");
        Integer space_id=space.getId();
        //获取作者信息
        User user= (User) session.getAttribute("user");
        String author=user.getUsername();
        //获取member_id就是用户id
        Integer member_id=user.getId();

        //新上传的文件下载数为0
        Contribute contributelastId=contributeService.findLastId();
        Integer  contribute_id=contributelastId.getId()+1;
        System.out.println("贡献id=========="+contribute_id);
        Integer downloadcount=0;
        //设置请求和响应的编码统一为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //拿到编辑器的内容
        String content = request.getParameter("editorValue");
        //如果不为空
        if(content != null){
            //将内容设置进属性
            request.setAttribute("content",content);
            //转发到content.jsp
            //request.getRequestDispatcher("content").forward(request, response);
        }else{
            response.getWriter().append("内容为空!");
        }
        //数据库命令
        resourceService.insertResource(title,content,author,detail,label,createdate,updatetime,member_id,space_id);
        //获取资源id  findLastId
        Resources last=resourceService.findLastId();
        Integer resource_id=last.getId();
        System.out.println("==========="+resource_id);
        //插入贡献
        Contribute contribute=new Contribute();

        contribute.setTitle(title);
        contribute.setContent(content);
        contribute.setUpdatetime(updatetime);
        contribute.setCreatetime(createdate);
        contribute.setLabel(label);
        contribute.setSpace_id(space_id);
        contribute.setMember_id(member_id);
        contribute.setStatus(2);

        contributeService.insertContribute(contribute);
        System.out.println("resource--file===="+file);
        if (!file.isEmpty()||file!=null) {
            System.out.println("进来！！！！");
            // 获取文件名
            String filename = file.getOriginalFilename();
            System.out.println("上传的文件名为：" + filename);
            //获取文件的大小
            double filesize=file.getSize();
            // 文件上传后的路径
            String filePath=session.getServletContext().getRealPath("/filelist/"+ filename);
            File dest = new File(filePath);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);

            documentService.insertDocument(filename,filesize,createdate,downloadcount,member_id,resource_id,space_id,contribute_id);
            int i=documentService.insertDocument(filename,filesize,createdate,downloadcount,member_id,resource_id,space_id);
            System.out.println("文件resource---i="+i);
        }
        return "redirect:space-resource";
    }

    //根据附件id删除附件信息1
    @RequestMapping(value="deleteFile")
    public String deleteFile(Document dd)throws Exception{
        Integer id=dd.getId();
        Integer resource_id=dd.getResource_id();
        documentService.deleteFile(id);
        return "redirect:space-resource-show?id="+resource_id;
    }

    //根据附件id删除附件信息2
    @RequestMapping(value="deletefilelist")
    public String deletefilelist(Document dd)throws Exception{
        Integer id=dd.getId();
        documentService.deleteFile(id);
        return "redirect:space-resource-filelist";
    }

    //添加评论信息
    @RequestMapping(value="/goToComment",method = RequestMethod.POST)
    public String goToComment(Integer resource_id,Integer author_id,Comment comment,HttpSession session){
        System.out.println();
        Date createdate=new Date();
        comment.setCreatedate(createdate);
        comment.setAuthor_id(author_id);
        comment.setResource_id(resource_id);
        commentService.addComment(comment);
        return "redirect:space-resource-show?id="+resource_id;
    }

    //删除评论信息
    @RequestMapping(value="/deleteComment")
    public String deleteComment(int comment_id,int resource_id){
        commentService.deleteCommentById(comment_id);
        return "redirect:space-resource-show?id="+resource_id;
    }

    //添加回复信息
    @RequestMapping(value="/reply",method = RequestMethod.POST)
    public String replyComment(int resource_id,int comment_id,Reply reply,HttpSession session) {
        Date createdate=new Date();
        reply.setCreatedate(createdate);
        //获取回复人的id
        User user= (User) session.getAttribute("user");
        Integer author_id=user.getId();
        reply.setAuthor_id(author_id);
        //回复给那位成员:
        reply.setMember_id(1);
        reply.setComment_id(comment_id);
        replyService.addReply(reply);
        return "redirect:space-resource-show?id="+resource_id;
    }

    //删除回复信息
    @RequestMapping(value="/deleteReply")
    public String deleteReply(int reply_id,int resource_id){
        replyService.deleteReplyById(reply_id);
        return "redirect:space-resource-show?id="+resource_id;
    }

}
